#!/usr/bin/perl

use English;

my $path = shift || '.';
my $DUP_PATH = "$path/dup";
my $MATCH_EXPR="(201[0123])-?([01][0-9])-?([0-3][0-9])";
my $BASE_SAVEPATH = "/Users/sparkyr/Pictures";
my $METADATA_CMD = "mdls -raw -name kMDItemFSCreationDate";

opendir (DIR, $path) or die "Can't open $path";
while (defined(my $file = readdir(DIR))) {
	my $fc = substr $file, 0, 1;
	my $ext = substr $file, -4;
# Uncomment this to break after raw timestamp files
#	if ($fc > '1') { exit; }
	# we only play with non-dot files.
	# we only play with jpg and mp4 files.
	if ($fc eq '.') {
#		print "Dotfile: $file\n";
		next;
	}
	if ($ext eq '.jpg' || $ext eq '.mp4') {
		print "$file";
		if (-f $file) {
			my $filepath = "$path/$file";
			my $savepath;
			if ($file =~ m/$MATCH_EXPR/) {
				$savepath = "$BASE_SAVEPATH/$1-$2-$3";
			} else {
				$savepath = $BASE_SAVEPATH . '/' . (split ' ', `$METADATA_CMD $filepath`)[0];
			}
			my $newfilename = "$savepath/$file";
			print "--> $newfilename\n";
			if (-f $newfilename) {
				print "$newfilename already exists\n";
				rename $filepath, "$DUP_PATH/$filepath";
			} else {
				if (!-d $savepath) {
					mkdir $savepath || die "Can't create directory $savepath\n";
				}
				rename $filepath, $newfilename || die "Can't create file $newfilename\n";
			}
		}
	}
}
closedir DIR